﻿using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Diagnostics;
using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;

namespace MQ_WechatCustomContact
{
    /// <summary>
    /// 外部联系人
    /// </summary>
    public class ExternalContact : ICustomContact
    {
        private ConsumeConfig _consumeConfig;
        private string logTitle = "externalcontact";
        private RequestAppSecret _appSecret;
        private string _SoftwareVersion = string.Empty;

        public ExternalContact(RequestAppSecret appSecret)
        {
            _appSecret = appSecret;
            _SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });

        }
        public async Task Excute(ConsumeConfig consumeConfig)
        {
            _consumeConfig = consumeConfig;

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            //拉数据
            try
            {
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】开始去：取数据，对应的dbid={_consumeConfig.DBId}");
                var list = await PullData();
                if (list == null||list.Count==0)
                {
                    stopwatch.Stop();
                    Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】没有拉取到数据哟");
                    return;
                }
                //批量获取外部联系人
                await GetBatchExternalContactDetail(list);

                stopwatch.Stop();
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
            }
            catch (Exception ex)
            {

                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                Console.WriteLine($"【{logTitle}】:{ex.Message}");
            }
        }
        /// <summary>
        /// 接数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<UserOutput>> PullData()
        {
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",_consumeConfig.FKId },
                {"is_user_contact",1 }
            };
            var result = await new ApiRequestClient(_appSecret).
                GetResponse<List<UserOutput>>(_consumeConfig.Domain,
                "wxgroup.account.manager.boundwxaccountoperlist", dic);
            if (result.Success)
            {
                var ret = (IResponse<List<UserOutput>>)result;
                return ret.Content;
            }
            return null;

        }
        /// <summary>
        /// 批量拉取外部联系人
        /// </summary>
        /// <returns></returns>
        private async Task GetBatchExternalContactDetail(List<UserOutput> list)
        {
            foreach (var item in list)
            {
                await GetBatchExternalContactDetail(item, string.Empty);                
            }


        }
        /// <summary>
        /// 递归批量拉取外部联系人
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cursor"></param>
        /// <returns></returns>
        private async Task GetBatchExternalContactDetail(UserOutput item, string cursor)
        {
            var dic = new Dictionary<string, object>()
            {
                {"fk_id",_consumeConfig.FKId },
                {"db_id",_consumeConfig.DBId },
                {"user_id",item.WXUserId },
                {"cursor",cursor }
            };
            var result = await new ApiRequestClient(_appSecret).
            GetResponse<JObject>(_consumeConfig.WechatDomain,
            "bind_user_relation", dic, "/wx/customer/list", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);

            if (!result.Success) return;

            var re = ((IResponse<JObject>)result).Content;
            await Push(re, item);
            if (!re.ContainsKey("cursor")) return;

            cursor = re["cursor"].ToString();
            if (string.IsNullOrEmpty(cursor)) return;

            await GetBatchExternalContactDetail(item, cursor);

        }
        /// <summary>
        /// 推数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task Push(JObject obj, UserOutput item)
        {
            var xml = Json.JsonToXml(obj, "root");
            var dic = new Dictionary<string, object>()
                {
                    {"fk_id",_consumeConfig.FKId },
                    {"follow_userid",item.WXUserId },
                    {"XML",xml.OuterXml }
                };

           var result=  await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.store.customer.synccustomers", dic);
            if (!result.Success)
            {
                Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString() }");
            }


        }
    
    }
}
